import Toast from 'tdesign-miniprogram/toast/index';

const stripeImg = `https://cdn-we-retail.ym.tencent.com/miniapp/order/stripe.png`;
import { getGoods, createOrder, checkCreateOrder } from '../../../services/good/index';
// import data from 'custom-tab-bar/data';
Page({
  data: {
    placeholder: '备注信息',
    stripeImg,
    loading: false,
    // 收获地址
    agentUserId: '',
    contactAddr: '',
    contactHouseNo: '',
    contactName: '',
    contactPhone: '',
    memo: '',
    list: [],
    totalSalePrice: 0,
    type: '',
  },

  payLock: false,
  noteInfo: [],
  tempNoteInfo: [],
  onLoad(options) {
    this.setData({
      loading: true,
      type: options.type,
    });
  },
  onShow() {
    this.init();
  },
  onInputValue(e) {
    const { value } = e.detail;
    this.setData({
      contactPhone: value,
    });
  },
  onInputNameValue(e) {
    const { value } = e.detail;
    this.setData({
      contactAddr: value,
    });
  },
  onInputGuigeValue(e) {
    const { value } = e.detail;
    this.setData({
      contactHouseNo: value,
    });
  },
  onInputOrtValue(e) {
    const { value } = e.detail;
    this.setData({
      contactName: value,
    });
  },
  onInputlongDescValue(e) {
    const { value } = e.detail;
    this.setData({
      memo: value,
    });
  },
  prevOrder(data) {
    return new Promise((resolve, reject) => {
      checkCreateOrder({
        agentUserId: data.agentUserId,
        productList: data.productList,
      })
        .then((res) => {
          if (res.status) {
            resolve(res);
          }
        })
        .catch((err) => {
          Toast({
            context: this,
            selector: '#t-toast',
            message: err.message,
            icon: '',
            duration: 1000,
          });
          setTimeout(() => {
            reject(err);
          }, 200);
        });
    });
  },
  submitOrder() {
    const { contactAddr, contactHouseNo, contactName, contactPhone, memo } = this.data;
    if (!contactAddr) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '联系人地址',
        icon: '',
        duration: 1000,
      });
      return;
    }
    if (!contactHouseNo) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '联系人门牌号',
        icon: '',
        duration: 1000,
      });
      return;
    }
    if (!contactPhone) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '联系人姓名',
        icon: '',
        duration: 1000,
      });
      return;
    }
    const productList = wx.getStorageSync('order.goodsRequestList');
    const productListData = JSON.parse(productList) || [];
    const role = wx.getStorageSync('role');
    const query = {
      agentUserId: role.userId,
      quantity: productListData.length,
      contactAddr: contactAddr,
      contactHouseNo: contactHouseNo,
      contactName: contactName,
      contactPhone: contactPhone,
      memo: memo,
      productList: productListData,
    };
    this.checkOrderStore(query);
  },
  // 创建订单
  createOrderStore(query) {
    createOrder(query)
      .then((res) => {
        if (res.status) {
          wx.setStorageSync('order.goodsRequestList', '');
          wx.setStorageSync('carList', '');
          wx.showToast({
            title: '购买成功',
            icon: 'none',
            duration: 2000,
          });
          setTimeout(function () {
            wx.switchTab({
              url: '/pages/home/home',
            });
          }, 1500);
        }
      })
      .catch((err) => {
        wx.showToast({
          title: '服务器出错',
          icon: 'none',
          duration: 2000,
        });
        setTimeout(function () {
          wx.navigateBack({
            delta: -1,
          });
        }, 200);
      });
  },
  // 预检查下单
  async checkOrderStore(query) {
    await this.prevOrder(query);
    this.createOrderStore(query);
  },

  getDetail(promiseArr, arr) {
    const that = this;
    const { type } = that.data;
    Promise.all(promiseArr).then((res) => {
      if (res.length > 0) {
        for (let i = 0; i < res.length; i++) {
          res[i].data.price = res[i].data.price > 0 ? this.priceInt(res[i].data.price).join('.') : 0;
          that.data.totalSalePrice += Number(res[i].data.price) * arr[i].value;
        }
        this.setData({
          list: arr,
          totalSalePrice: this.data.totalSalePrice,
        });
      }
    });
    // getGoods({ kid: spuId }).then((res) => {
    //   const details = res.data;
    //   details.price = details.price > 0 ? this.priceInt(details.price).join('.') : 0;
    //   for (const item of arr) {
    //     this.data.totalSalePrice += Number(details.price) * item.value;
    //     debugger;
    //   }
    //   this.setData({
    //     list: arr,
    //     totalSalePrice: this.data.totalSalePrice,
    //   });
    // });
  },
  priceInt(price) {
    const pArr = [];
    price = Math.round(price * 10 ** 8) / 10 ** 8; // 恢复精度丢失
    price = Math.ceil(price); // 向上取整
    pArr[0] = price >= 100 ? `${price}`.slice(0, -2) : '0';
    pArr[1] = `${price + 100}`.slice(-2);
    this.setData({ pArr });
    return pArr;
  },
  init() {
    const arr = [];
    const that = this;
    const data = wx.getStorageSync('order.goodsRequestList') || [];
    const list = JSON.parse(data) || [];
    setTimeout(function () {
      if (list && list.length > 0) {
        for (const item of list) {
          arr.push(
            getGoods({
              kid: item.key,
            }),
          );
        }
        that.getDetail(arr, list);
      }
    }, 100);
  },
});
